package com.document.dto;

import lombok.Data;
import jakarta.validation.constraints.NotBlank;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

// src/main/java/com/im/dto/DatasourceConnection.java
@Data
public class DatasourceConnection {
    @NotBlank(message = "数据库类型不能为空")
    private String dbType;

    @NotBlank(message = "主机地址不能为空")
    private String host;

    private Integer port = 3306;

    @NotBlank(message = "数据库名不能为空")
    private String database;

    @NotBlank(message = "用户名不能为空")
    private String username;

    @NotBlank(message = "密码不能为空")
    private String password;

    public String getJdbcUrl() {
        switch (dbType.toLowerCase()) {
            case "mysql":
                return String.format(
                        "jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai",
                        host, port, database
                );
            case "postgresql":
                return String.format("jdbc:postgresql://%s:%d/%s", host, port, database);
            default:
                throw new IllegalArgumentException("不支持的数据库类型: " + dbType);
        }
    }

    // 添加连接测试方法
    public boolean testConnection() {
        try (Connection conn = DriverManager.getConnection(getJdbcUrl(), username, password)) {
            return conn.isValid(5); // 5秒超时
        } catch (SQLException e) {
            return false;
        }
    }
}